/**
 * 无害化申报
 * @constructor
 */
function HarmlessReport() {
}
let img = "";
HarmlessReport.init = function () {
    let vm = new Vue({
        el: "#customModule",
        data: {
            //实体
            harmlessReportID:"",
            dead:"",
            suserName:"",
            declareTime:"",
            animal:"",
            user:"",
            createTime:"",
            cause:"",
            code:"",
            dhannel:"",
            driver:"",
            transportationTime:"",
            phone:"",
            car:"",
            method:"",
            person:"",
            processingTime:"",
            img:"",
            declareImage:"",
            batch:"", //批次号
            batchList:[],
            species:"",
            reserve:"",
            menstruation:"",
            lactation:"",
            conservation:"",
            commodity:"",
            livestock:"",
            //搜索值
            timeInterval: "",
            statusCondition:-1,
            //附加属性
            clickState: "",
            roleID: "",
            isAdd: "true",
            roleList: ""
        },
        created() {
            //日期区间选择
            laydate.render({
                elem: '#declareTimeCondition',
                range: true,
                done:function (value) {
                    console.log("时间选择器",value.split(" - "))
                    vm.timeInterval = value;
                }
            });
            laydate.render({
                elem: '#validity',
                theme: 'molv',
                type:'date',
                done:function (value) {
                    vm.validity = value;
                }
            });
            this.roleID = $.cookie('RoleIds');
            self = this;
            window.show = self.show;
            window.edit = self.edit;
            window.del = self.del;
        },
        mounted() {
            this.initBootStrapSource();
            this.initBatch();
        },
        methods: {
            initBootStrapSource() {
                $('#tableList').bootstrapTable({
                    url: '/harmlessReport/tableSearch',
                    method: 'post',
                    toolbar: "#toolbar",
                    sidePagination: 'server',
                    dataField: "data",
                    striped: true,
                    pagination: true,
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    sortable: true,
                    sortName: 'createDateTime',
                    sortOrder: "desc",
                    search: false,
                    showRefresh: true,
                    showColumns: true,
                    showExport: true,
                    showToggle: true,
                    queryParamsType: 'undefined',
                    queryParams: function queryParams(params) {
                        return {
                            pageSize: params.pageSize,      //页面大小
                            pageIndex: params.pageNumber,   //页码
                            sort: params.sortName,      //排序列名
                            sortOrder: params.sortOrder, //排位命令（desc，asc）
                            timeInterval:$("#declareTimeCondition").val(),
                            status:$("#statusCondition").val()
                        };
                    },
                    onLoadSuccess: function (data) {
                        //Help.alertSuccMessage("数据加载完毕");
                    },
                    onLoadError: function (status) {
                        // Help.alertErrorMessage("数据加载出错");
                    },
                    columns: [
                        {
                            title: '序号',//标题  可不加
                            align: "center",
                            width: 40,
                            formatter: function (value, row, index) {
                                var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                                var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                                return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                            }
                        },
                        {field: 'declareTime', title: '申报日期', align: 'center'},
                        {field: 'suserName', title: '申报人', align: 'center'},
                        {field: 'animal', title: '病死畜禽种类', align: 'center'},
                        {field: 'dead', title: '病死畜禽数量', align: 'center'},
                        {field: 'createTime', title: '上报日期', align: 'center'},
                        {field: 'user', title: '上报人', align: 'center'},
                        {field: 'cause', title: '死亡原因', align: 'center'},
                        {
                            field: 'dhannel', title: '处理途径', align: 'center',
                            formatter:function(value){
                                let s;
                                if (value === 0){
                                    s = "自行处理";
                                }else if (value === 1){
                                    s = "集中处理";
                                }
                                return s;
                            }
                        },
                        {
                            field: 'method', title: '处理方式', align: 'center',
                            formatter:function(value){ // 0焚烧、1深埋、2化致、3集中无害化处理
                                let s;
                                if (value === 0){
                                    s = "焚烧";
                                }else if (value === 1){
                                    s = "深埋";
                                }else if (value === 2){
                                    s = "化致";
                                }else if (value === 3){
                                    s = "集中无害化处理";
                                }
                                return s;
                            }
                        },
                        {field: 'harmlessName', title: '无害化处理企业', align: 'center'},
                        {field: 'transportationTime', title: '运输时间', align: 'center'},
                        {field: 'processingTime', title: '处理时间', align: 'center'},
                        {
                            field: 'status', title: '状态', align: 'center',
                            formatter:function(value){
                                let s;
                                if (value === 0){
                                    s = "待上报";
                                }else if (value === 1){
                                    s = "待运输";
                                }else if (value === 2){
                                    s = "待处理";
                                }else if (value === 3){
                                    s = "已处理";
                                }
                                return s;
                            }
                        },
                        {
                            title: '操作', align: 'center',
                            formatter: function (value, row, index) {
                                let optionHtml;
                                if (row.status === 0){ //待上报，可以编辑删除
                                    optionHtml = "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='edit(" + JSON.stringify(row) + ")'  title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                                    optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='del(" + JSON.stringify(row) + ")' title=\"删除\"><i class=\"fa fa-remove\"></i>删除</a>";
                                }else {
                                    optionHtml =  " <a class=\"btn btn-info btn-xs\" href=\"javascript:void(0)\"  onclick='show(" + JSON.stringify(row) + ")' title=\"删除\">查看处理详情</a>";
                                }
                                return optionHtml;
                            }
                        }
                    ]
                });
            },
            /**
             * 查询
             */
            search() {
                vm.refresh();
            },
            /**
             * 重置
             */
            reset() {
                vm.timeInterval = "";
                $("#declareTimeCondition").val("");
                vm.statusCondition = -1;
                $("#statusCondition").val("-1");
                vm.refresh();
            },
            /**
             * 编辑
             * @param data
             */
            edit(data) {
                console.log("animalTpye",data);
                vm.harmlessReportID = data.harmlessReportID;
                vm.animalTpye = data.animalTpye;
                img = data.declareImage;
                vm.batch = data.batch;
                vm.species = data.species;
                vm.reserve = data.reserve;
                vm.menstruation = data.menstruation;
                vm.lactation = data.lactation;
                vm.conservation = data.conservation;
                vm.commodity = data.commodity;
                vm.livestock = data.livestock;
                //隐藏文件选择
                // $("#uploadImages").css("display","none");
                //图片回显
                $("#showImage").css("display","");
                $("#showImage").attr("src",data.declareImageUrl);

                $("#showImage2").css("display","");
                $("#showImage2").attr("src",data.declareImageUrl);
                vm.clickState = "edit";
                if ($("#type").val() == 1){
                    $('#myModalAdd').modal('show');
                    $('#myModalAdd2').modal('hide');
                }else {
                    $('#myModalAdd2').modal('show');
                    $('#myModalAdd').modal('hide');
                }
            },
            /**
             * 查看详情
             * @param data
             */
            show(data) {
                console.log("data",data);
                vm.suserName = data.suserName;
                vm.declareTime = data.declareTime;
                vm.animal = data.animal;
                vm.dead = data.dead;
                vm.user = data.user;
                vm.createTime = data.createTime;
                vm.cause = data.cause;
                vm.code = data.code;
                vm.dhannel = data.dhannel;
                vm.driver = data.driver;
                vm.transportationTime = data.transportationTime;
                vm.car = data.car;
                vm.phone = data.phone;
                vm.method = data.method;
                vm.person = data.person;
                vm.processingTime = data.processingTime;
                vm.img = data.img;
                vm.declareImage = data.declareImageUrl;
                $('#myModalAdd1').modal('show');
            },
            /**
             * 删除
             * @param data
             */
            del(data) {
                swal({
                    title: "确认是否删除",
                    text: "是否确认要删除该条记录？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "删除",
                    cancelButtonText: "取消",
                    closeOnConfirm: false
                }, function () {
                    let url = "/harmlessReport/del";
                    let pm = {
                        harmlessReportID: data.harmlessReportID
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            swal("删除成功!", "请继续操作", "success");
                            vm.refresh();
                        } else {
                            swal("删除失败!", "请重试", "error");
                        }
                    });
                });
            },
            /**
             * 新增
             */
            addRecord() {
                vm.harmlessReportID = "";
                vm.batch = "";
                vm.animalTpye = "";
                vm.species = "";
                vm. reserve = "";
                vm. menstruation = "";
                vm. lactation = "";
                vm. conservation = "";
                vm. commodity = "";
                vm.dead = "";
                vm.livestock = "";
                //显示文件选择
                // $("#uploadImages").css("display","");
                var file = $("#uploadImages");
                file.after(file.clone().val(""));
                file.remove();
                //隐藏图片
                $("#showImage").css("display","none");

                // $("#uploadImages2").css("display","");
                var file2 = $("#uploadImages2");
                file2.after(file2.clone().val(""));
                file2.remove();
                //隐藏图片
                $("#showImage2").css("display","none");
                img = "";
                vm.clickState = "add";
                if ($("#type").val() == 1){
                    $('#myModalAdd').modal('show');
                    $('#myModalAdd2').modal('hide');
                }else {
                    $('#myModalAdd2').modal('show');
                    $('#myModalAdd').modal('hide');
                }
            },
            /**
             * 保存
             */
            saveRecord() {
                if(!validateForm()) return false;
                if(!validateForm2()) return false;
                let pm = {
                    harmlessReportID:vm.harmlessReportID,
                    batch:vm.batch,
                    animalTpye:vm.animalTpye,
                    declareImage:img,
                    species:vm.species,
                    reserve:vm.reserve,
                    menstruation:vm.menstruation,
                    lactation:vm.lactation,
                    conservation:vm.conservation,
                    commodity:vm.commodity,
                    livestock:vm.livestock,
                    batchName:$("#batch").find("option:selected").text()
                }
                console.log("pm",pm)
                if (vm.clickState === "edit") {
                    let url = "/harmlessReport/edit";
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            $('#myModalAdd').modal('hide');
                            $('#myModalAdd2').modal('hide');
                            swal("修改成功!", "请继续操作", "success");
                            this.refresh();
                        }
                    }).catch(e => {
                        console.log(e);
                        swal("修改失败!", "请重试", "error");
                    });
                } else if (vm.clickState === "add") {
                    let url = "/harmlessReport/add";
                    axios.post(url, pm).then(data => {
                        $('#tableList').bootstrapTable(('refresh'));
                        if (data.data.code === "200") {
                            $('#myModalAdd').modal('hide');
                            $('#myModalAdd2').modal('hide');
                            swal("添加成功!", "请继续操作", "success");
                            this.refresh();
                        }
                    }).catch(e => {
                        console.log(e);
                        swal("添加失败!", "请重试", "error");
                    });
                }
            },
            initBatch(){
                let url = "/animalnumber/getBatch";
                axios.get(url).then(data => {
                    if (data.data.code === "200") {
                        this.batchList = data.data.data;
                    }
                }).catch(e => {
                    console.log('error',e);
                });
            },
            refresh() {
                $('#tableList').bootstrapTable(('refresh'));
            }
        }
    });
};
//表单验证
function validateForm() {
    //validate方法参数可选
    return $("#myform").validate({
        rules: {
            batch: {
                required: true,//必填
                minlength: 1, //最少1个字符
                number: true, //必须是数字
            },
            uploadImages: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
        },
        //错误信息提示
        messages: {
            batch: {
                required: "(必填)",
                minlength: "最少1位",
                number: "必须输入数字",
            },
            uploadImages: {
                required: "(必填)",
                minlength: "最少1位",
            },
        },
    }).form();
}
//表单验证
function validateForm2() {
    //validate方法参数可选
    return $("#myform2").validate({
        rules: {
            livestock: {
                required: true,//必填
                minlength: 1, //最少1个字符
                number: true, //必须是数字
            },
            uploadImages2: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
        },
        //错误信息提示
        messages: {
            livestock: {
                required: "(必填)",
                minlength: "最少1位",
                number: "必须输入数字",
            },
            uploadImages2: {
                required: "(必填)",
                minlength: "最少1位",
            },
        },
    }).form();
}
/**
 * 图片上传
 */
function ImportImages() {
    if ($("#uploadImages").val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: '/image/uploadImages',
        secureuri: false,
        fileElementId: "uploadImages",
        dataType: 'json',
        success: function (data, status) {
            img = data.url;
            //隐藏文件选择
            // $("#uploadImages").css("display","none");
            //图片回显
            $("#showImage").css("display","");
            $("#showImage").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败", e);
        }

    });
}
function ImportImages2() {
    if ($("#uploadImages2").val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: '/image/uploadImages',
        secureuri: false,
        fileElementId: "uploadImages2",
        dataType: 'json',
        success: function (data, status) {
            img = data.url;
            //隐藏文件选择
            // $("#uploadImages").css("display","none");
            //图片回显
            $("#showImage2").css("display","");
            $("#showImage2").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败", e);
        }
    });
}